from Products.Five import BrowserView
from plonetheme.apkntheme.settings import TWG_FEED_BASE_URL,\
										  TWG_FEED_PORTAL_TYPES,\
										  TWG_MENU,\
										  TWG_PARAMETER_DEFAULT_VALUES,\
										  TWG_ROOT,\
										  TWG_SPACES_ROOT,\
										  TWG_FEED_PARAMETERS

from plonetheme.apkntheme.utils import feedparser
from plonetheme.apkntheme.utils.tools import get_host_url
from plonetheme.apkntheme import logger

from urllib import quote

def qt(v):
	return quote(v, safe="+")


class WorkingGroupFeeds(BrowserView):
	"""
	Render working Group Feeds based on spec in ../settings.py
	"""

	def getFeedItems(self, feed_url):
		feed = feedparser.parse(feed_url)
		logger.info("Processing feed at address %s", feed_url)
		return feed.entries

	def getFeedMetadata(self):
		feed_data = []
		feed_base_url = get_host_url(self.request)
		for twg_item in TWG_MENU:
			feed_title = twg_item['title']
			feed_id = twg_item['id']
			feed_base_address = twg_item['address']
			feed_section = {
							'feeds':[], 
							'title': feed_title, 
							'id': feed_id
							}
			for feed_type in TWG_FEED_PORTAL_TYPES:
				feed_info = {}
				url_params = [qt(fp) + '=' + qt(feed_type['params'].get(fp, '')) 
				for fp in TWG_FEED_PARAMETERS]
				feed_url_base = '/'.join((
									feed_base_url,
									TWG_SPACES_ROOT,
									feed_base_address,
									TWG_FEED_BASE_URL))
				url_params_nmlz = '&'.join(url_params)
				feed_url_final = '?'.join((feed_url_base, url_params_nmlz))
				feed_info['feed_url'] = feed_url_final
				feed_info['feed_title'] = feed_type['title']
				feed_info['feed_items'] = self.getFeedItems(feed_url_final)
				feed_section['feeds'].append(feed_info)
			feed_data.append(feed_section)
		return feed_data
